<template>
  <div class="timeInShop">
    <!-- 页面主体 -->
    <g-main>
      <div class="timeInShop-wrapper">
        <!-- 店铺数据总览 -->
        <div class="store-summary">
          <div class="summary-title clearfix">
            <div class="name">
              <span class="pageName">逛店时长</span>
              <el-tooltip class="instructions" effect="dark" placement="bottom-start">
                <i class="iconfont">&#xe72d;</i>
                <div slot="content">
                  人均逛店时长=日进店人数总停留时长/日进店人数(排重)
                  <br>
                  <br>
                  次均逛店时长=日进店人数总停留时长/日进店人次
                </div>
              </el-tooltip>
            </div>
          </div>
          <el-row class="summary-main clearfix">
            <el-col :span="8" style="margin-right:20px;">
              <el-date-picker :clearable="false"
                              v-model="choosenDate"
                              type="daterange"
                              size="small"
                              value-format="yyyy-MM-dd"
                              @change = changeDateRange()
                              :picker-options="pickerOptions"
                              range-separator="至"
                              start-placeholder="开始日期"
                              end-placeholder="结束日期">
              </el-date-picker>
            </el-col>
            <el-col :span="8" class="timeOptions">
              <span :class="[{ active: activeDateOption === 'first' }, 'option']" @click=handleDate(0)>7天</span>
              <span :class="[{ active: activeDateOption === 'second' }, 'option']" @click=handleDate(1)>14天</span>
              <span :class="[{ active: activeDateOption === 'third' }, 'option']" @click=handleDate(2)>30天</span>
            </el-col>
          </el-row>
        </div>
      </div>
      <div class="compass-tabs">
        <el-tabs v-model="activeTabsName">
          <!-- tab - 进店人数 -->
          <el-tab-pane label="人均逛店时长" name="aveTimeInShopView">
            <div class="customer-number-view data-view">
              <div class="panel-title">
                <span>趋势图</span>
              </div>
              <div class="panel-charts">
                <customer-number-echart :options="stayTimeEchartInitOptionOfRange"></customer-number-echart>
              </div>
              <div class="panel-title">
                <span>详细数据</span>
                <span class="save-csv-link" @click="SaveDateToDesktop">
                  <i class="iconfont">&#xe68e;</i>
                  导出CSV</span>
              </div>
              <div class="panel-table">
                <el-table :data="currTableData"
                          border
                          size="small"
                          highlight-current-row
                          style="width: 100%">
                  <el-table-column prop="time"
                                   label="时间"
                                   align="center"
                                   sortable
                                   width="180">
                  </el-table-column>
                  <el-table-column prop="stayTimeOfAvg"
                                   align="right"
                                   sortable
                                   label="人均逛店时长（秒）">
                    <template slot-scope="scope">{{ scope.row.stayTimeOfAvg !== null && scope.row.stayTimeOfAvg !== undefined ? scope.row.stayTimeOfAvg : '0' }}</template>
                  </el-table-column>
                  <el-table-column prop="stayTimeOfTimes"
                                   align="right"
                                   sortable
                                   label="次均逛店时长（秒）">
                    <template slot-scope="scope">{{ scope.row.stayTimeOfTimes !== null && scope.row.stayTimeOfTimes !== undefined ? scope.row.stayTimeOfTimes : '0' }}</template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="次均逛店时长" name="aveTimeInShopViewOfTimes">
            <div class="customer-times-view data-view">
              <div class="panel-title">
                <span>趋势图</span>
              </div>
             <div class="panel-charts">
                <customer-times-echart :options="TimesEchartInitOptionOfRange"></customer-times-echart>
              </div>
              <div class="panel-title">
                <span>详细数据</span>
                <span class="save-csv-link" @click="SaveDateToDesktop">
                  <i class="iconfont">&#xe68e;</i>
                  导出CSV</span>
              </div>
              <div class="panel-table">
                <el-table :data="currTableData"
                          border
                          size="small"
                          highlight-current-row
                          style="width: 100%">
                  <el-table-column prop="time"
                                   label="时间"
                                   align="center"
                                   sortable
                                   width="180">
                  </el-table-column>
                  <el-table-column prop="stayTimeOfAvg"
                                   align="right"
                                   sortable
                                   label="人均逛店时长（秒）">
                    <template slot-scope="scope">{{ scope.row.stayTimeOfAvg !== null && scope.row.stayTimeOfAvg !== undefined ? scope.row.stayTimeOfAvg : '0' }}</template>
                  </el-table-column>
                  <el-table-column prop="stayTimeOfTimes"
                                   align="right"
                                   sortable
                                   label="次均逛店时长（秒）">
                    <template slot-scope="scope">{{ scope.row.stayTimeOfTimes !== null && scope.row.stayTimeOfTimes !== undefined ? scope.row.stayTimeOfTimes : '0' }}</template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </g-main>
  </div>
</template>
<script type="text/ecmascript-6">
// components
import Main from '@/components/main'
import customerEchart from '@/components/echarts'
// element-ui
import { Row, Col, DatePicker, Tooltip, Tabs, TabPane, Table, TableColumn } from 'element-ui'

import Moment from 'moment'
import { mapGetters } from 'vuex'
// api
import { APIGetStayTimeData } from '@/api/trajectory.js'

import Config from '@/utils/config.js'

// 单天图表配置============================
import stayTimeEchartInitOptionOfRange from './stayTimeEchartInitOptionOfRange.js'
import TimesEchartInitOptionOfRange from './TimesEchartInitOptionOfRange.js'

export default {
  name: 'timeinshop',

  components: {
    // elementUI component
    elRow: Row,
    elCol: Col,
    elDatePicker: DatePicker,
    elTooltip: Tooltip,
    elTabs: Tabs,
    elTabPane: TabPane,
    elTable: Table,
    elTableColumn: TableColumn,
    // 项目自定义组件
    gMain: Main,
    customerNumberEchart: customerEchart,
    customerTimesEchart: customerEchart
  },

  created () {
    this.APIGetStayTimeData(this.choosenDate)
  },

  data () {
    return {
      // default date option
      activeDateOption: 'first',
      // default tab name
      activeTabsName: 'aveTimeInShopView',
      stayTimeData: null,
      // echarts option
      stayTimeEchartInitOptionOfRange: null,
      TimesEchartInitOptionOfRange: null,
      // 用户所选时间
      choosenDate: [Moment().subtract(7, 'day').format('YYYY-MM-DD'), Moment().subtract(1, 'day').format('YYYY-MM-DD')],
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() > Moment().subtract(1, 'day')
        }
      }
    }
  },

  computed: {
    ...mapGetters([
      'mallId',
      'token'
    ]),
    currTableData () {
      const data = []
      const stayTimeData = this.stayTimeData || []
      for (let key in stayTimeData) {
        let stats = stayTimeData[key]
        let item = {}
        item.time = key
        item.stayTimeOfAvg = stats ? stats.customer_num_stay_time : null
        item.stayTimeOfTimes = stats ? stats.customer_times_stay_time : null
        data.push(item)
      }
      return data
    }
  },

  methods: {
    // 下载表格
    SaveDateToDesktop () {
      window.location.href = `${Config.CURR_REQ_URL}/api/shops/${this.mallId}/stay-time/export?api_token=${this.token}&start_date=${this.choosenDate[0]}&end_date=${this.choosenDate[1]}`
    },
    // 表格总计
    // tableSummaryMethod ({columns, data}) {
    //   const sumTxt = '合计'
    //   let customerNumberTotal = 0
    //   let customerTimesTotal = 0
    //   for (let inx = 0; inx < data.length; inx++) {
    //     if (!data) {
    //       break
    //     }
    //     const item = data[inx]
    //     customerNumberTotal += item.stayTimeOfAvg
    //     customerTimesTotal += item.stayTimeOfTimes
    //   }
    //   let res = []
    //   res.push(sumTxt)
    //   res.push(customerNumberTotal)
    //   res.push(customerTimesTotal)
    //   return res
    // },
    // 设置人均逛店时长option
    setStayTimeChartsOption (values) {
      let option = Object.assign({}, stayTimeEchartInitOptionOfRange)
      let xAxisArr = []
      for (let key in values) {
        xAxisArr.unshift(key)
      }
      option.xAxis = Object.assign({}, option.xAxis, { data: xAxisArr })
      let data = []
      for (let key in values) {
        data.unshift(values[key].customer_num_stay_time)
      }
      option.series[0].data = data
      this.stayTimeEchartInitOptionOfRange = option
    },
    // 设置次均逛店时长option
    setTimesChartsOption (values) {
      // customerNumberEchartOption
      let xAxisArr = []
      for (let key in values) {
        xAxisArr.unshift(key)
      }
      let option = Object.assign({}, TimesEchartInitOptionOfRange)
      option.xAxis = Object.assign({}, option.xAxis, { data: xAxisArr })
      let data = []
      for (let key in values) {
        data.unshift(values[key].customer_times_stay_time)
      }
      option.series[0].data = data
      this.TimesEchartInitOptionOfRange = option
    },
    // 用户选择时间
    changeDateRange () {
      this.APIGetStayTimeData(this.choosenDate)
    },
    // 时间快捷选择
    handleDate (n) {
      let a = Moment().subtract(1, 'day').format('YYYY-MM-DD')
      switch (n) {
        case 0:
          this.activeDateOption = 'first'
          let b = Moment().subtract(7, 'day').format('YYYY-MM-DD')
          this.choosenDate = [b, a]
          break
        case 1:
          this.activeDateOption = 'second'
          let c = Moment().subtract(14, 'day').format('YYYY-MM-DD')
          this.choosenDate = [c, a]
          break
        case 2:
          this.activeDateOption = 'third'
          let d = Moment().subtract(30, 'day').format('YYYY-MM-DD')
          this.choosenDate = [d, a]
          break
        default:
          this.activeDateOption = 'first'
          this.choosenDate = [b, a]
      }
      this.APIGetStayTimeData(this.choosenDate)
    },

    // api ======================================================
    APIGetStayTimeData (dateRange) {
      APIGetStayTimeData({ shop: this.mallId, startDate: dateRange[0], endDate: dateRange[1] })
        .then((res) => {
          this.stayTimeData = res.data.stats
          this.setStayTimeChartsOption(res.data.stats)
          this.setTimesChartsOption(res.data.stats)
        })
    }
  }
}
</script>

<style lang="less" rel="stylesheet/less" scoped>
  // scoped
  .timeInShop {
    .timeInShop-wrapper{
      box-sizing: border-box;
      box-shadow: 0 2px 3px 0 rgba(0, 0, 0, 0.2);
      .store-summary {
        width: 100%;
        height: auto;
        box-sizing: border-box;
        background-color: #FFF;
        padding: 10px 20px;
        .summary-title {
          padding: 10px 0;
          height: 30px;
          line-height: 30px;
          border-bottom: 1px solid #DFDFDF;
          overflow: hidden;
          .name {
            .pageName{
              font-weight: bold;
              font-size: 18px;
            }
            .instructions {
            color: #777;
           }
          }
          .date {
            float: left;
            margin-left: 30px;
            color: #777;
            font-size: 14px;
          }
        }
        .summary-main {
          margin-top: 10px;
          padding: 10px;
          .timeOptions{
            height: 32px;
            line-height: 32px;
            .option{
              margin-right: 20px;
              font-size: 14px;
              color: black;
              cursor: pointer;
              &.active{
                color: rgb(30, 184, 39);
              }
            }
          }
          .summary-item {
            box-sizing: border-box;
            padding: 20px;
            width: 100%;
            background-color: #FFF;
            border: 1px solid #DFDFDF;
            .label {
              color: #777;
              font-size: 14px;
              .iconfont {
                margin-left: 5px;
              }
            }
          }
        }
      }
    }
    .compass-tabs {
      box-shadow: 0 2px 3px 0 rgba(0, 0, 0, 0.2);
      box-sizing: border-box;
      margin-top: 20px;
      padding: 10px 20px;
      width: 100;
      background-color: #FFF;
      .data-view {
        .panel-title {
          font-size: 16px;
          .instructions {
            color: #777;
          }
          .save-csv-link {
            float: right;
            cursor: pointer;
            font-size: 13px;
            color: #0269c8;
          }
        }
        .panel-charts {
          padding: 20px 0;
          width: 100%;
          height: 350px;
        }
        .panel-table {
          padding: 20px 0;
          width: 100%;
        }
      }
    }
  }
</style>
